import { Button, message } from "antd";
import { FC, useState } from "react";
import { MathJax, MathJaxContext } from "better-react-mathjax";
import TrainProblemExplain from "./TrainProblemExplain";
import { getCookie, setCookie } from "@utils/StorageUtil";

const TrainProblemChoice: FC<any> = ({ problem, refreshProblem, submitTrain }) => {
  // 1. 状态管理
  const choiceItems = [problem.choiceA, problem.choiceB, problem.choiceC, problem.choiceD]; // 选项列表
  const [selectedIndex, setSelectedIndex] = useState(-1); // 当前选中索引

  //记录回答状态
  const [isAnswered, setIsAnswered] = useState(false);

  // 2. 选项点击处理
  const handleOptionClick = (index: any) => {
    setSelectedIndex(index); // 记录当前选中项
  };

  // 3. 提交处理
  const handleSubmit = () => {
    if (selectedIndex !== -1) {
      // 这里可以处理提交逻辑，比如发送到服务器
      var choiceItem = choiceItems[selectedIndex];
      if(problem.answer === choiceItem) {
        var train = Number.parseInt(getCookie("problemTrain"));
        setCookie("problemTrain", (train + 1).toString());
        message.success("回答正确");
        submitTrain("choice", problem.problemId, "true"); // 提交正确答案 
      } else {
        message.error("已记录为薄弱点，后续系统会重点训练");
        submitTrain("choice", problem.problemId, "false"); // 提交错误答案
      }
      setIsAnswered(true); // 标记为已回答
    }
  };

  if(isAnswered) {
    return <TrainProblemExplain problem={problem} refreshProblem={refreshProblem} submitTrain={submitTrain} />; // 如果已回答，显示答案 
  }

  return (
    <>
      {/* 动态选项按钮 */}
      {choiceItems.map((item, index) => (
        <MathJaxContext>
          <Button
            key={index}
            type={selectedIndex === index ? "default" : "primary"}
            onClick={() => handleOptionClick(index)}
            size="large"
            style={{
              marginLeft: "20%",
              width: "60%",
              height: 50,
              background: selectedIndex === index ? "#52c41a" : "#fff",
              borderColor: "#52c41a",
              fontWeight: selectedIndex === index ? "bold" : "normal",
              color: selectedIndex === index ? "#fff" : "#52c41a",
              borderRadius: 8,
              fontSize: 16,
              marginTop: 20,
            }}
          >
            <MathJax>{item}</MathJax>
          </Button>
        </MathJaxContext>
      ))}
      <Button
        type="primary"
        onClick={handleSubmit}
        disabled={selectedIndex === -1}
        size="large"
        style={{
          marginLeft: "20%",
          width: "60%",
          height: 50,
          background: "#52c41a",
          borderRadius: 8,
          fontSize: 16,
          marginTop: 30,
        }}
      >
        提交答案
      </Button>
    </>
  );
};

export default TrainProblemChoice;
